package com.roger.myHome.interceptor;

import com.roger.myHome.exception.DuplicateException;
import com.roger.myHome.exception.MyParseException;
import com.roger.myHome.log.PrintlnErrorLog;
import com.roger.myHome.util.StringUtils;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * 统一异常处理类
 */
@Order(Ordered.HIGHEST_PRECEDENCE)
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(DuplicateException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public String handleDuplicateException(DuplicateException e) {
        PrintlnErrorLog.printlnErrorLog("数据重复异常", e, "查看错误日志");
        Map<String,String> hashMap = new HashMap<String, String>();
        hashMap.put("result", e.getMessage());
        return StringUtils.getJSONString(hashMap);
    }

    @ExceptionHandler(MyParseException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public String handleParseException(MyParseException e) {
        PrintlnErrorLog.printlnErrorLog("解析日期异常", e, "查看错误日志");
        Map<String,String> hashMap = new HashMap<String, String>();
        hashMap.put("result", e.getMessage());
        return StringUtils.getJSONString(hashMap);
    }


    /**
     * 其它运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public String handleRuntimeException(RuntimeException e) {
        PrintlnErrorLog.printlnErrorLog("系统异常", e, "查看错误日志");
        Map<String,String> hashMap = new HashMap<String,String>();
        hashMap.put("result", "系统错误!");
        return StringUtils.getJSONString(hashMap);
    }

    /**
     * 其它所有异常（最终兜底）
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public String handleException(RuntimeException e) {
        PrintlnErrorLog.printlnErrorLog("系统异常", e, "查看错误日志");
        Map<String,String> hashMap = new HashMap<String, String>();
        hashMap.put("result", "系统错误!");
        return StringUtils.getJSONString(hashMap);
    }


}
